<?php

/**
 * Description of Weixin
 *
 * @author guo
 */

namespace App\Libs;

use App\User;
use Hash;
use Image;
use Cache;

class Weixin {

    //put your code here
    public $weixinId;

    //__set()方法用来设置私有属性 
    public function __set($name, $value) {
        $this->$name = $value;
    }

//__get()方法用来获取私有属性 
    public function __get($name) {
        return $this->$name;
    }

    public function UserInfo($openId = null) {
        if ($openId === null) {
            return "";            
        }
        $user = User::where('weixinCode', $openId)->get();
        if (count($user) === 0) {            
            User::create([
                'name' => 'wx',
                'email' => time() . '@qq.com',
                'role' => 'wx',
                'password' => Hash::make($openId . 'ss'),
                'weixinCode' => $openId,
            ]);
            $id = User::where('weixinCode', $openId)->first()->id;
            return json_encode(['status' => 1, 'userid' => $id]);
        } else {
            $userDetail = User::where('weixinCode', $openId)->where('name', '<>', 'wx')->get();
            if (count($userDetail) > 0) {
                return json_encode(['status' => 3, 'userid' => $userDetail[0]->id]);
            } else {
                $userDetail = User::where('weixinCode', $openId)->first();
                return json_encode(['status' => 2, 'userid' => $userDetail->id]);
            }
        }
    }

    public function updateUserInfo($openId, $nickName, $sex , $avatar) {
        $user = User::where('weixinCode', $openId)->first();
        if (is_null($user)) {
            return 0;
        } else {
            $user->name = $nickName;
            $user->sex = $sex;
            $user->avatar = $avatar;
            $user->save();
            return 1;
        }
    }

    public function id($weixinCode) {
        $user = User::where('weixinCode', $weixinCode)->first();
        if (count($user)) {
            return $user->id;
        }
        return 0;
    }

    public function getImage($urlImg) {
        $img = Image::make($urlImg);
        // resize the image to a width of 300 and constrain aspect ratio (auto height)
        $img->resize(200, null, function ($constraint) {
            $constraint->aspectRatio();
        });
        $img->save('/root/datas/darling/images/temp/' . $fileName);
    }

}
